<template>
  <el-dropdown
    ref="dropRef"
    popper-class="merak-table-dropdown"
    trigger="click"
    :placement="props.hasSlot ? 'bottom-end' : 'left-start'"
    @command="command => emit('change', command)"
    @visible-change="visibled => !!visibled && emit('click')"
  >
    <el-button class="merak-table-handler" size="small" text circle>
      <MerakIcon size="14">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
          <path
            d="M12,16A2,2 0 0,1 14,18A2,2 0 0,1 12,20A2,2 0 0,1 10,18A2,2 0 0,1 12,16M12,10A2,2 0 0,1 14,12A2,2 0 0,1 12,14A2,2 0 0,1 10,12A2,2 0 0,1 12,10M12,4A2,2 0 0,1 14,6A2,2 0 0,1 12,8A2,2 0 0,1 10,6A2,2 0 0,1 12,4Z"
          />
        </svg>
      </MerakIcon>
    </el-button>
    <template #dropdown>
      <el-dropdown-menu v-loading="!!props.loading">
        <template v-for="item in props.handles">
          <el-dropdown-item
            v-if="!!item.visible ? !!item.visible?.(props.row) : true"
            :command="item.type"
            :icon="item.icon"
            :divided="item.divided"
            :disabled="item.disabled?.(props.row)"
            :style="{ color: item.color }"
          >
            {{ typeof item.text === "string" ? item.text : item.text?.(props.row) }}
          </el-dropdown-item>
        </template>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script setup lang="ts">
import type { MerakXTableDropdown, MerakXTableData } from "./index";

import { ref, watch } from "vue";

import { ElDropdown, ElDropdownMenu, ElDropdownItem, ElButton } from "element-plus";

import MerakIcon from "../MerakIcon/index.vue";

const props = defineProps<{
  row: MerakXTableData;
  visible: boolean;
  hasSlot?: boolean;
  handles: MerakXTableDropdown[];
  loading?: boolean;
}>();

const emit = defineEmits<{
  click: [];
  change: [command: string];
}>();

const dropRef = ref<InstanceType<typeof ElDropdown>>();

watch(
  () => props.visible,
  () => {
    if (!props.visible) {
      dropRef.value?.handleClose();
    }
    // if (props.visible) {
    //   dropRef.value?.handleOpen();
    // } else {
    //   dropRef.value?.handleClose();
    // }
  }
);
</script>
